package com.fly.docker.job;

import java.util.List;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.docker.service.DockerService;
import com.fly.docker.sse.SSEServer;
import com.google.common.collect.Lists;
import com.spotify.docker.client.messages.Container;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class PushJob
{
    ObjectMapper objectMapper = new ObjectMapper();
    
    String last = "";
    
    @Autowired
    DockerService dockerService;
    
    @Scheduled(cron = "0/5 * * * * ?")
    public void run()
    {
        try
        {
            //变化才推送
            List<Container> containers = dockerService.getContainers();
            String message = objectMapper.writeValueAsString(containers);
            if (!StringUtils.equals(last, message))
            {
                log.info("###### pushData again");
                SSEServer.batchSendMessage(message);
                last = message;
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 此推送数据vue3展示页面user.html
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected List<User> users()
    {
        String now = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        Long sequence = 1L;
        return Lists.newArrayList(new User().setUserId(sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence++).setCreateTime(now),
            new User().setUserId(sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence++).setCreateTime(now),
            new User().setUserId(sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence++).setCreateTime(now),
            new User().setUserId(sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence++).setCreateTime(now),
            new User().setUserId(sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence++).setCreateTime(now));
    }
}
